<template>
  <div class="login-container">
    <!-- Logo区域 -->
    <div class="logo-section">
      <div class="logo-wrapper">
        <div class="logo-circle">
          <svg class="logo-icon" viewBox="0 0 24 24">
            <path fill="currentColor" d="M20,19V7H4V19H20M20,3A2,2 0 0,1 22,5V19A2,2 0 0,1 20,21H4A2,2 0 0,1 2,19V5C2,3.89 2.9,3 4,3H20M13,17V15H18V17H13M9.58,13L5.57,9H8.4L11.7,12.3C12.09,12.69 12.09,13.33 11.7,13.72L8.42,17H5.59L9.58,13Z" />
          </svg>
        </div>
      </div>
      <h1 class="app-title">老薛SSH工具</h1>
      <p class="app-subtitle">移动端专业版</p>
    </div>

    <!-- 登录表单 -->
    <div class="form-section">
      <van-form @submit="handleLogin">
        <van-cell-group inset>
          <van-field
            v-model="loginForm.username"
            name="username"
            label="账号"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请输入用户名' }]"
            left-icon="manager"
            clearable
          />
          
          <van-field
            v-model="loginForm.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请输入密码' }]"
            left-icon="lock"
            clearable
          />
          
          <van-field
            v-model="loginForm.totpToken"
            name="totpToken"
            label="验证码"
            placeholder="Google验证码（选填）"
            type="digit"
            maxlength="6"
            left-icon="shield-o"
            clearable
          />
        </van-cell-group>

        <div class="button-wrapper">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="登录中..."
            size="large"
          >
            登录
          </van-button>
        </div>
      </van-form>

      <!-- 提示信息 -->
      <div class="tips">
        <van-icon name="info-o" />
        <span>如已启用Google验证器，请输入验证码</span>
      </div>
    </div>

    <!-- 版权信息 -->
    <div class="footer">
      <p>&copy; 2025 老薛SSH工具</p>
      <p>Version 1.0.0</p>
    </div>

  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { useAuthStore } from '@/stores/auth'
import authAPI from '@/api/auth'

const router = useRouter()
const authStore = useAuthStore()

// 表单数据
const loginForm = ref({
  username: '',
  password: '',
  totpToken: ''
})

const loading = ref(false)

// 登录处理
const handleLogin = async () => {
  if (loading.value) return
  
  try {
    loading.value = true
    console.log('📱 开始登录:', loginForm.value.username)
    
    const response = await authAPI.login(loginForm.value)
    console.log('📦 登录响应:', response)
    
    if (response.requireTotp && !loginForm.value.totpToken) {
      showToast({
        message: '请输入Google验证码',
        position: 'top'
      })
      return
    }
    
    // 保存token和用户信息到store（数据在response.data中）
    const { token, user } = response.data
    console.log('📤 准备保存:', { token, user })
    authStore.setAuth(token, user)
    
    showToast({
      type: 'success',
      message: '登录成功',
      position: 'top'
    })
    
    console.log('✅ 登录成功，跳转首页')
    console.log('🔍 Store状态:', {
      token: authStore.token ? '已设置' : '未设置',
      isAuthenticated: authStore.isAuthenticated
    })
    
    // 使用 nextTick 确保状态更新后再跳转
    await new Promise(resolve => setTimeout(resolve, 100))
    
    router.push('/servers')
  } catch (error) {
    console.error('❌ 登录失败:', error)
    showToast({
      message: error.response?.data?.message || '登录失败',
      position: 'top'
    })
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow-y: auto;
}

/* Logo区域 */
.logo-section {
  text-align: center;
  margin-top: 60px;
  margin-bottom: 40px;
}

.logo-wrapper {
  display: inline-block;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.logo-circle {
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.logo-icon {
  width: 40px;
  height: 40px;
  color: white;
}

.app-title {
  font-size: 28px;
  font-weight: bold;
  color: white;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.app-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
}

/* 表单区域 */
.form-section {
  flex: 1;
}

.van-cell-group {
  margin-bottom: 20px;
}

.button-wrapper {
  padding: 0 16px;
  margin-top: 30px;
}

.van-button--large {
  height: 50px;
  font-size: 16px;
  font-weight: bold;
}

.tips {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
  gap: 6px;
}

/* 底部 */
.footer {
  text-align: center;
  padding: 20px 0;
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
  margin-top: auto;
}

.footer p {
  margin: 4px 0;
}

/* Vant样式覆盖 */
:deep(.van-cell) {
  font-size: 15px;
}

:deep(.van-field__label) {
  width: 60px;
  color: #646566;
}

:deep(.van-field__control) {
  font-size: 15px;
}
</style>

